package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    //从spring容器中动态注入对象
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;


    /**
     *  1.创建bucket
     *  2.设定访问权限 public
     *  3.文件上传
     *      lg:  http://192.168.126.128:9000/test/title.jpg
     *      lg:  http://192.168.126.128:9000/test/2024/11/11/uuid.jpg
     *  4.需要 1.分目录存储  2.使用UUID防止文件重名.
     *  5.实现文件上传  返回特定的url地址
     */
    @Override
    public String upload(MultipartFile file) {
        try {
            //1.创建bucket
            createBucket();

            //2.生成目录路径
            String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            //3.生成uuid
            String uuid = UUID.randomUUID().toString().replace("-","");
            //4.获取文件的后缀  abc.jpg ===> .jpg
            String subType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //5.生成文件名称    /2024/10/01/uuid.jpg
            String objectName = datePath + uuid + subType;

            //6.实现文件上传
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(objectName)
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);
            //System.out.println("文件上传成功");

            //7.返回能够访问图片的url地址
            // http://192.168.126.128:9000/test/title.jpg
            String url = minioProperties.getEndpoint() + "/" +minioProperties.getBucketName() + objectName;
            //System.out.println("图片的访问地址:"+url);
            return url;

        } catch (Exception e) {
            System.out.println("文件上传有误");
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private void createBucket() throws Exception {
        //%s 表示这里是一个变量 未来被替换
        String config  = """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(minioProperties.getBucketName());


        boolean flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        if(!flag){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            //设定策略
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(config).build());
        }
    }

}
